<?php
/**
 * 本页面用于单个采集
 * 仅供测试用 
 */
	include_once('../sys/sys.php');
	header('Content-Type: text/html; charset=utf-8');

	$tid = $_GET['tid'];
	if(!is_numeric($tid) || $tid < 0){
		show_normal_mesR('TAG ID错误','TAG ID错误','TAG查询');
	}
	$url = 'http://xs.178.com/' . $tid . '/index.shtml';
	
	
	//分离URL以及ID
	$id = $tid;
	//定义公用变量
//	if (substr($url,-1)!="/")
//		$url.="/";
	$url_pre = $url;
	$pic_url_pre = 'http://xs.178.com/';
	//获取URL内容
//	$url = "1.htm";
	$content = 	file_get_contents($url);
	//$content = 	mb_convert_encoding(file_get_contents($url),"UTF-8","GB2312");
	
	//获取名称
	$name = explode('var g_lnovel_name = \'',$content);
	$name = $name[1];
	$name = explode('\'',$name);
	$name = $name[0];



	//获取最后更新时间
	$dt = explode('更新时间：',$content);
	$dt = $dt[1];
	$dt = explode('</span>',$dt);
	$dt = strtotime(trim($dt[0]));
	if ($dt <= 0) {
		$dt = 0;
	}
	
	//获取URL列表
	$urls = explode('<!--novel_cover_box-->',$content);
	$urls = $urls[1];
	$urls = explode('<div class="probable_like">',$urls);
	$urls = $urls[0];
	$urls = explode('<div class="clearfix"></div>',$urls);
	unset($urls[0]);
	unset($urls[count($urls)]);
	
	//获取当前总数
	$numn = count($urls);
	//插入分类信息
	$where = 'AND id= ' . $id .'';
	$result = $DB->build_and_exec_query(
		array('select' => 'COUNT(*) as max','from'   => '178_tags','where'	=> "1 " . $where ,)
	);	
	//当已经存在的时候更新日期
	if ($result['max'] > 0) {
		
	}
	//当不存在时插入
	else{
		do_taginsert($id,$dt,$name,0);
	}
	//获取数据库COUNT
	$where = 'AND id= ' . $id .'';
		$result = $DB->build_and_exec_query(
			array('select' => 'count','from'   => '178_tags','where'	=> "1 " . $where ,)
		);	
	$dbcount = $result['count'];
	
	//入库
	foreach ($urls as $k=>$v) {
		if ($k <= $dbcount) {
				continue;
		}
		//获取下载链接
		$utf8dl = explode('">下载1',$v);
		$utf8dl = explode('<a href=".',$utf8dl[0]);
		$utf8dl = $utf8dl[1];
		$utf8dl = $pic_url_pre . $tid . $utf8dl;
		$gbdl = str_replace(".txt","_GBK.txt",$utf8dl);
		//获取名称
		$cname = explode('点此下载TXT</a></span>',$v);
		$cname = explode('</li>',$cname[1]);
		$cname = $cname[0];
		do_photoinsert($id,$utf8dl,$gbdl,$cname);
	}
	
	
	//更新计数
	$where = 'id= ' . $id .'';
	$DB->do_update('178_tags',
		array(					  
		   'lastupdate'				=> $dt,
		   'count'					=> count($urls),
		 ),
		 $where
	);
	
	
	
	function do_taginsert($id,$lu,$name,$count){
		global $DB;
		$DB->do_insert( '178_tags', array( 'id'			=> $id,
								   'lastupdate'				=> $lu,
								   'name'					=> $name,
								   'count'					=> $count,
								 )		);
		if ($result === false) {
			show_normal_mesR('无法添加当前漫画','添加出错','添加');
		}
	}
	
	
	function do_photoinsert($uid,$url,$gburl,$name){
		global $DB;
		$DB->do_insert( '178_photos', array( 
								   'uid'				=> $uid,
								   'url'					=> $url,
								   'gburl'					=> $gburl,								
								   'name'					=> $name,
								 )		);
		if ($result === false) {
			show_normal_mesR('无法添加当前漫画','添加出错','添加');
		}
	}
	
	echo "采集完毕";
	
	
	exit;
	
	
?>